package app

import (
	"fmt"
	"github.com/go-redis/redis/v8"
	"gorm.io/gorm"
	"telemple_web/app/core/config"
	"telemple_web/app/core/db"
	rds "telemple_web/app/core/redis"
)

var Config config.Model

func Init(configPath string) error {
	//配置文件，也有第三方viper可以实现类似功能
	err := Config.LoadConfig(configPath)
	if err != nil {
		return err
	}
	fmt.Println("configDef:", Config)

	return nil
}

func RedisR(key ...string) *redis.Client {
	return rds.Load("read", &Config, key...)
}

func RedisW(key ...string) *redis.Client {
	return rds.Load("write", &Config, key...)
}

func DBW(key ...string) *gorm.DB {
	k := "default"
	if len(key) > 0 {
		k = key[0]
	}
	conf, ok := Config.DB[k]
	if !ok {
		panic(fmt.Sprintf("db DBW conf not found: %s", k))
	}

	cacheKey := fmt.Sprintf("%s_write", k)
	return db.Load(conf.Write, conf.Log, cacheKey)
}

func DBR(key ...string) *gorm.DB {
	k := "default"
	if len(key) > 0 {
		k = key[0]
	}
	conf, ok := Config.DB[k]
	if !ok {
		panic(fmt.Sprintf("db DBR conf not found: %s", k))
	}
	cacheKey := fmt.Sprintf("%s_read", k)
	return db.Load(conf.Read, conf.Log, cacheKey)
}
